import { Store } from "pinia"

export const isEmpty = (value: any) => ['undefined', 'null', 'NaN', ''].includes(String(value))

export const objToParam = (obj = {}) => {
   const paramList:string[] = []

  for (const [key, value] of Object.entries(filterObject(obj))) {
     paramList.push(`${key}=${value}`)
   }

  return paramList.join('&')
}

export const filterObject = (obj = {}) => {
  const computeObj: ObjectType = {}

  for (const [key, value] of Object.entries(obj)) {
    if (!isEmpty(value)) {
      computeObj[key] = value
    }
  }
  return computeObj
}

export const bindActionCreators = async (actionCreators: ObjectType, store: Store<string, ObjectType>) => {
  const json = await actionCreators.fetchApi()
  
  return actionCreators.success
    ? actionCreators.success(json)
    : store[actionCreators.type]?.(actionCreators.pipe?.(json) ?? json)
  // const code = json.code

  // if ([0, 1001].includes(code)) {
  //   return actionCreators.success
  //     ? actionCreators.success(json)
  //     : store[actionCreators.type]?.(actionCreators.pipe?.(json) ?? json)
  // }

  // if (actionCreators.fail) {
  //   return actionCreators.fail(json)
  // }

  // return alert(json.msg ?? '服务异常, 请稍后再试!')
}

export function debounce (func: (...arg: any) => any, wait = 1000) {
  let timer: number
  
  return function (this: any) {
    let lastThis = this
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(function () {
      func.call(lastThis, arguments)
    }, wait);
  }
}

export function throttle(func: (...arg: any) => any, wait = 1000) {
  let preTime = 0

  return function (this: any) {
    const context = this
    const currentTime = new Date().getTime()

    if (currentTime - preTime > wait) {
      func.call(context, arguments)
      preTime = currentTime
    }
  }
}